/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.ruoyi.pingan.fymodule.busManage.busSubAcctBinding.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.pingan.config.PayConfig;
import com.ruoyi.pingan.config.TaskExecutePoolConfig;
import com.ruoyi.pingan.enums.CommonSortOrderEnum;
import com.ruoyi.pingan.exception.CommonException;
import com.ruoyi.pingan.fymodule.account.enums.CodeEnum;
import com.ruoyi.pingan.fymodule.account.service.ISxoSafetyLogService;
import com.ruoyi.pingan.fymodule.account.service.ISxoSafetyUserService;
import com.ruoyi.pingan.fymodule.account.util.HttpResult;
import com.ruoyi.pingan.fymodule.account.util.PaPayUtil;
import com.ruoyi.pingan.fymodule.busManage.busSubAcct.entity.busSubAcct;
import com.ruoyi.pingan.fymodule.busManage.busSubAcct.service.BusSubAcctService;
import com.ruoyi.pingan.fymodule.busManage.busSubAcctBinding.entity.busSubAcctBinding;
import com.ruoyi.pingan.fymodule.busManage.busSubAcctBinding.mapper.busSubAcctBindingMapper;
import com.ruoyi.pingan.fymodule.busManage.busSubAcctBinding.param.*;
import com.ruoyi.pingan.fymodule.busManage.busSubAcctBinding.service.BusSubAcctBindingService;
import com.ruoyi.pingan.fymodule.exception.BusinessException;
import com.ruoyi.pingan.fymodule.thirdpa.api.IBaseClient;
import com.ruoyi.pingan.fymodule.thirdpa.api.impl.MntMbrBindRelateAcctBankCodeApi;
import com.ruoyi.pingan.fymodule.thirdpa.api.impl.UnbindRelateAcctApi;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaMemberService;
import com.ruoyi.pingan.fymodule.thirdpa.util.CommonResult;
import com.ruoyi.pingan.page.CommonPageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 商户子账户绑定Service接口实现类
 *
 * @author zjf
 * @date  2025/07/10 13:50
 **/
@Service
public class busSubAcctBindingServiceImpl extends ServiceImpl<busSubAcctBindingMapper, busSubAcctBinding> implements BusSubAcctBindingService {


    @Autowired
    private PaMemberService paMemberService;

    @Autowired
    private ISxoSafetyUserService sxoSafetyUserService;

    @Autowired
    private BusSubAcctService busSubAcctService;
    @Autowired
    private PayConfig payConfig;

    @Autowired
    private ISxoSafetyLogService sxoSafetyLogService;

    @Autowired
    private TaskExecutePoolConfig taskExecutePoolConfig;


    @Override
    public Page<busSubAcctBinding> page(busSubAcctBindingPageParam busSubAcctBindingPageParam) {
        QueryWrapper<busSubAcctBinding> queryWrapper = new QueryWrapper<busSubAcctBinding>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(busSubAcctBindingPageParam.getMemberName())) {
            queryWrapper.lambda().eq(busSubAcctBinding::getMemberName, busSubAcctBindingPageParam.getMemberName());
        }
        if (ObjectUtil.isNotEmpty(busSubAcctBindingPageParam.getMemberGlobalId())) {
            queryWrapper.lambda().eq(busSubAcctBinding::getMemberGlobalId, busSubAcctBindingPageParam.getMemberGlobalId());
        }
        if(ObjectUtil.isAllNotEmpty(busSubAcctBindingPageParam.getSortField(), busSubAcctBindingPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(busSubAcctBindingPageParam.getSortOrder());
            queryWrapper.orderBy(true, busSubAcctBindingPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(busSubAcctBindingPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(busSubAcctBinding::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public CommonResult<String> unbind(busSubAcctBindingUnbindParam busSubAcctBindingUnbindParam) {
        CommonResult cr = new CommonResult();
        busSubAcctBinding busSubAcctBinding = this.queryEntity(busSubAcctBindingUnbindParam.getId());

        if (busSubAcctBinding == null) {
            cr.setCode(500);
            cr.setMsg("ID错误");
            return cr;
        }
        LambdaQueryWrapper<busSubAcct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(busSubAcct::getUserId,busSubAcctBinding.getUserId());
        queryWrapper.eq(busSubAcct::getTranNetMemberCode,busSubAcctBinding.getTranNetMemberCode());
        busSubAcct busSubAccts = busSubAcctService.getOne(queryWrapper);
        if (busSubAccts == null) {
            cr.setCode(500);
            cr.setMsg("当前没有会员入驻，请先入驻");
            return cr;
        }


        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6065");
        json.put("FunctionFlag", "1");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        json.put("TranNetMemberCode", busSubAcctBinding.getTranNetMemberCode());
        json.put("SubAcctNo", busSubAccts.getSubAcctNo());
        json.put("MemberAcctNo", busSubAcctBinding.getMemberAcctNo());



        IBaseClient baseClient = new UnbindRelateAcctApi(sxoSafetyLogService, taskExecutePoolConfig);
        HttpResult httpResult = baseClient.execute(json);
        if (httpResult.getStatus() != CodeEnum.SUCCESS.getCode()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), httpResult.getError());
        }

        JSONObject obj = JSON.parseObject(httpResult.getBody());
        JSONObject extenddata = obj.getJSONObject(PaPayUtil.extenddata) == null ? obj.getJSONObject(PaPayUtil.edata) : obj.getJSONObject(PaPayUtil.extenddata);

        if (extenddata.get(PaPayUtil.code) != null && !extenddata.getString(PaPayUtil.code).equals(PaPayUtil.code_000000)) {
            cr.setCode(500);
            cr.setMsg(extenddata.getString(PaPayUtil.TXN_RETURN_MSG));
            return cr;
        }
        if (extenddata.get(PaPayUtil.TXN_RETURN_CODE) != null && !extenddata.getString(PaPayUtil.TXN_RETURN_CODE).equals(PaPayUtil.code_000000)) {
            cr.setCode(500);
            cr.setMsg(extenddata.getString(PaPayUtil.TXN_RETURN_MSG));
            return cr;
        }

        busSubAcctBinding.setSepJzbAcceptSeqNo(extenddata.getString("FrontSeqNo"));
        this.updateById(busSubAcctBinding);
        cr.setCode(200);
        cr.setMsg("操作成功");
        return cr;

    }

    @Override
    public void withdrawalaccount(busSubAcctBindingWithdrawalAccountParam busSubAcctBindingWithdrawalAccountParam) {

        busSubAcctBinding busSubAcctBinding = this.queryEntity(busSubAcctBindingWithdrawalAccountParam.getId());
        LambdaQueryWrapper<busSubAcct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(busSubAcct::getUserId,busSubAcctBinding.getUserId());
        queryWrapper.eq(busSubAcct::getTranNetMemberCode,busSubAcctBinding.getTranNetMemberCode());
        busSubAcct busSubAccts = busSubAcctService.getOne(queryWrapper);
        if(busSubAccts!=null){

            JSONObject json = new JSONObject();
            json.put("TxnCode", "KFEJZB6138");
            json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
            json.put("SubAcctNo", busSubAccts.getSubAcctNo());
            json.put("MemberBindAcctNo", busSubAcctBindingWithdrawalAccountParam.getMemberBindAcctNo());
            json.put("AcctOpenBranchName", busSubAcctBindingWithdrawalAccountParam.getAcctOpenBranchName());
            json.put("CnapsBranchId", busSubAcctBindingWithdrawalAccountParam.getCnapsBranchId());
            json.put("EiconBankBranchId", busSubAcctBindingWithdrawalAccountParam.getEiconBankBranchId());


            IBaseClient baseClient = new MntMbrBindRelateAcctBankCodeApi(sxoSafetyLogService, taskExecutePoolConfig);
            HttpResult httpResult = baseClient.execute(json);
            if (httpResult.getStatus() != CodeEnum.SUCCESS.getCode()) {
                throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), httpResult.getError());
            }

            JSONObject obj = JSON.parseObject(httpResult.getBody());
            JSONObject extenddata = obj.getJSONObject(PaPayUtil.extenddata) == null ? obj.getJSONObject(PaPayUtil.edata) : obj.getJSONObject(PaPayUtil.extenddata);



        }






    }

//    @Override
//    public MemberBindTranItemArrayVo bindquery(busSubAcctBindingbindQueryParam busSubAcctBindingbindQueryParam) {
//
////        MemberBindTranItemArrayVo memberBindTranItemArrayVo = new MemberBindTranItemArrayVo();
////        memberBindTranItemArrayVo.setMemberAcctNo("11111");
////        memberBindTranItemArrayVo.setBankType("1");
////        memberBindTranItemArrayVo.setMemberName("中国银行");
////        memberBindTranItemArrayVo.setAcctOpenBranchName("湖里支行");
////        memberBindTranItemArrayVo.setMemberGlobalId("1");
////        memberBindTranItemArrayVo.setCnapsBranchId("55555");
////        memberBindTranItemArrayVo.setEiconBankBranchId("34353453");
////        memberBindTranItemArrayVo.setFundSummaryAcctNo("352653199562");
////        memberBindTranItemArrayVo.setMobile("13175826534");
////        return memberBindTranItemArrayVo;
//        busSubAcctBinding busSubAcctBinding = this.queryEntity(busSubAcctBindingbindQueryParam.getId());
//        MemberBindQueryDto memberBindQueryDto = new MemberBindQueryDto();
//        memberBindQueryDto.setQueryFlag("2");
//        memberBindQueryDto.setPageNum("1");
//        LambdaQueryWrapper<busSubAcct> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(busSubAcct::getUserId,busSubAcctBinding.getUserId());
//        queryWrapper.eq(busSubAcct::getTranNetMemberCode,busSubAcctBinding.getTranNetMemberCode());
//        busSubAcct busSubAccts = busSubAcctService.getOne(queryWrapper);
//
//        memberBindQueryDto.setSubAcctNo(busSubAccts.getSubAcctNo());
//        MemberBindQueryVo memberBindQueryVo =  paMemberService.memberBindQuery(memberBindQueryDto);
//
//        return memberBindQueryVo.getTranItemArray().get(0);
//    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(busSubAcctBindingAddParam busSubAcctBindingAddParam) {
        busSubAcctBinding busSubAcctBinding = BeanUtil.toBean(busSubAcctBindingAddParam, busSubAcctBinding.class);
        this.save(busSubAcctBinding);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(busSubAcctBindingEditParam busSubAcctBindingEditParam) {
        busSubAcctBinding busSubAcctBinding = this.queryEntity(busSubAcctBindingEditParam.getId());
        BeanUtil.copyProperties(busSubAcctBindingEditParam, busSubAcctBinding);
        this.updateById(busSubAcctBinding);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<busSubAcctBindingIdParam> busSubAcctBindingIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(busSubAcctBindingIdParamList, busSubAcctBindingIdParam::getId));
    }

    @Override
    public busSubAcctBinding detail(busSubAcctBindingIdParam busSubAcctBindingIdParam) {
        return this.queryEntity(busSubAcctBindingIdParam.getId());
    }

    @Override
    public busSubAcctBinding queryEntity(Long id) {
        busSubAcctBinding busSubAcctBinding = this.getById(id);
        if(ObjectUtil.isEmpty(busSubAcctBinding)) {
            throw new CommonException("商户子账户绑定不存在，id值为：{}", id);
        }
        return busSubAcctBinding;
    }






}
